import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:just_audio/just_audio.dart';
import 'package:demo/event/event_message.dart';
import 'package:demo/event/event_setting.dart';
import 'package:demo/views/base/base_controller.dart';
import 'package:demo/tools/tools_enum.dart';
import 'package:demo/tools/tools_sqlite.dart';
import 'package:demo/tools/tools_storage.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

class MsgChatController extends BaseController {
  // 键盘
  final KeyboardVisibilityController keyboard = KeyboardVisibilityController();
  // 文本输入
  final TextEditingController textController = TextEditingController();
  // 消息存储
  late Map<String, ChatHis> _dataMap;
  // 当前对象
  late LocalChat localChat;
  // 当前对象
  LocalUser localUser = ToolsStorage().local();
  // 初始化声音
  final AudioPlayer audioPlayer = AudioPlayer();
  // 滚动组件
  final AutoScrollController scrollController = AutoScrollController();
  // 刷新组件
  final PagingController<int, ChatHis> pagingController = PagingController(
    firstPageKey: 1,
  );
  // 通知标题
  late Rx<String> chatTitle = ''.obs;
  // 多选
  late RxBool configCheckBox = false.obs;
  // 多选集合
  final RxMap<String, ChatHis> checkboxList = RxMap();

  @override
  void onInit() {
    super.onInit();
    // 初始化
    _init();
    // 监听分页
    _listenPage();
    // 监听消息
    _listenMessage();
    // 监听设置
    _listenSetting();
  }

  // 初始化
  _init() {
    // 清空
    _dataMap = {};
    // 清空
    checkboxList.clear();
    // 清空
    localChat = ToolsStorage().chat();
    // 清空
    pagingController.refresh();
    // 标题组件
    chatTitle.value = localChat.title;
  }

  // 监听分页
  _listenPage() {
    pagingController.addPageRequestListener((pageKey) async {
      List<ChatHis> dataList = await ToolsSqlite().his.getPager(
            localChat.chatId,
            pageKey,
          );
      // 没有数据了
      if (dataList.isEmpty) {
        pagingController.appendLastPage([]);
        return;
      }
      // 组织数据
      for (var chatHis in dataList) {
        _dataMap[chatHis.msgId] = chatHis;
      }
      // 追加数据
      pagingController.appendPage(dataList, pageKey + 1);
    });
  }

  // 监听消息
  _listenMessage() {
    subscription?.cancel();
    subscription = EventMessage().listenHis.stream.listen((chatHis) {
      // 存储消息
      _dataMap[chatHis.msgId] = chatHis;
      // 获取数据
      List<ChatHis> dataList = pagingController.itemList ?? [];
      // 新消息
      pagingController.itemList = [chatHis] + dataList;
    });
  }

  // 监听设置
  _listenSetting() async {
    // 群组
    if (ChatTalk.group == localChat.chatTalk) {
      // 设置群聊
      _setGroup(localChat.chatId);
    }
    // 订阅
    eventStream?.cancel();
    eventStream = EventSetting().event.stream.listen((model) async {
      // 删除消息
      if (SettingType.remove == model.setting) {
        String chatId = model.primary;
        if (chatId != localChat.chatId) {
          return;
        }
        // 获取数据
        List<ChatHis> dataList = pagingController.itemList ?? [];
        List<String>? messageList = model.dataList;
        for (var msgId in messageList!) {
          // 重复消息
          if (!_dataMap.containsKey(msgId)) {
            continue;
          }
          // 移除
          dataList.remove(_dataMap[msgId]);
          // 移除
          _dataMap.remove(msgId);
        }
        pagingController.itemList = List.from(dataList);
      }
      // 清空消息
      else if (SettingType.clear == model.setting) {
        String current = ToolsStorage().chat().chatId;
        String chatId = model.primary;
        // 校验
        if (chatId != current) {
          return;
        }
        // 移除
        pagingController.itemList?.clear();
        // 刷新
        pagingController.refresh();
      }
      // 我的
      else if (SettingType.mine == model.setting) {
        // 重置信息
        localUser = ToolsStorage().local();
        // 更新对象
        if (localUser.userId != localChat.chatId) {
          return;
        }
        // 标题
        chatTitle.value = localUser.nickname;
      }
      // 好友
      else if (SettingType.friend == model.setting) {
        if (localChat.chatId != model.primary) {
          return;
        }
        // 查询好友
        ChatFriend? friend = await ToolsSqlite().friend.getById(model.primary);
        if (friend == null) {
          return;
        }
        // 重置
        localChat = ToolsStorage().chat();
        // 标题
        chatTitle.value = friend.nickname;
      }
      // 群聊
      else if (SettingType.group == model.setting) {
        if (localChat.chatId != model.primary) {
          return;
        }
        // 设置群聊
        _setGroup(model.primary);
      }
    });
  }

  // 设置群聊
  _setGroup(String groupId) async {
    // 查询群聊
    ChatGroup? group = await ToolsSqlite().group.getById(groupId);
    if (group == null) {
      return;
    }
    // 重置
    localChat = ToolsStorage().chat();
    // 标题
    chatTitle.value = group.groupName;
  }

  @override
  void onClose() {
    audioPlayer.stop();
    audioPlayer.dispose();
    scrollController.dispose();
    pagingController.dispose();
    // 关闭
    super.onClose();
  }
}
